package glory.xxd

import cn.hutool.json.JSONUtil
import jcifs.smb.NtlmPasswordAuthentication
import jcifs.smb.SmbFile
import net.sf.json.xml.XMLSerializer
import org.apache.commons.lang.StringEscapeUtils
import org.json.JSONArray
import org.json.JSONObject
import org.json.XML
import tsCIM.modelForInterface.ResultModel

/**
 * 数据格式转换工具类
 * Created by Administrator on 2018-01-22.
 */
class Utils {


    static def StringUtils

    static String getUUID() {
        return java.util.UUID.randomUUID()
    }

    static String getValueByXML(String xml, String property) {

        def responseInstance = new XmlParser().parseText(xml)// new XmlParser().parseText(aa)
        def body = responseInstance.Body
        def str = body."${property}".text()
        return str ?: ""
    }

    static String getValueByXML(groovy.util.Node node, String property) {
        def body = node.Body
        def str = body."${property}".text()
        return str ?: ""
    }

    static String getJsonByXML(String xml) {
        def json = org.json.XML.toJSONObject(xml)
        return json
    }

    /**
     *
     * @param xml
     * @param nodeName
     * @return
     */
    static String getJsonByXML(String xml, String nodeName) {
        def json = XML.toJSONObject(xml)
//        def json=org.json.JSONObject.getJSONArray(xml)
        def nodes = nodeName.split('/.')
        nodes.each { it ->
            json = json."${it}"
        }
        return json.toString()
    }

    /**
     *
     * @param xml
     * @param nodeName
     * @return
     */
    static JSONObject getJsonObjectByXML(String xml, String nodeName) {

        def json = org.json.XML.toJSONObject(xml)
        def nodes = nodeName.split('/.')
        //[Request,Body]
        nodes.each { it ->
            json = json."${it}"
        }
        return json
    }

    /**
     * getJsonObjectByXML
     * @param xml
     * @return
     */
    static JSONObject getJsonObjectByXML(String xml) {

        def json = XML.toJSONObject(xml)
        def Header = json.getJSONObject("Response").getJSONObject("Header")
        //println Header
        if ("SUCCESS".equals(String.valueOf(Header?.getString("RESULT")))) {
            json = json.getJSONObject("Response").getJSONObject("Body")
        } else {
            json = Header
        }
        return json
    }

    /**
     * getJsonObjectByXML
     * @param xml
     * @return
     */
    static net.sf.json.JSONObject getJsonObjectByXML_1(String xml) {

//        XmlMapper xmlMapper = new XmlMapper();
//        MaterialInfo2Entity tempValue = xmlMapper.readValue(xml, MaterialInfo2Entity.class);
//        println tempValue
//        def json = net.sf.json.JSONObject.fromObject(tempValue)

        XMLSerializer xmlSerializer = new XMLSerializer();

        def json = (net.sf.json.JSONObject) xmlSerializer.read(String.valueOf(xml));
        //此处转换后，直接没有最外层的节点Response
        //def Header = json.getJSONObject("Response").getJSONObject("Header")
        def Header = json.getJSONObject("Header")

        if ("SUCCESS".equals(String.valueOf(Header.getString("RESULT")))) {
            json = json.getJSONObject("Body")
            //针对SendEQPMeterial接口特殊处理2019-03-13 xxd
            //net.sf.json.JSONObject api转换后，去掉了多余的包裹层，要加上
            if(Header.get("MESSAGENAME") == "SendEQPMeterial"){
                def flag = json.get("MesMaterial")
                def MesMaterial = [:]
                Map<String,Object> Materials = new HashMap<>()
                if(!flag){
                    MesMaterial.put("MesMaterial", json.get("Materials"))
                    //Materials.put("Materials",MesMaterial)
                    json.put("Materials",MesMaterial)
                }
            }
        } else {
            json = Header
        }
        return json
    }

    /**
     * xml 转json
     * @param xml
     * @return
     */
    static net.sf.json.JSONObject Xml2Json(String xml) {
        net.sf.json.JSON json = ResultModel.getResultModel()
//        try {
            XMLSerializer xmlSerializer = new XMLSerializer();
            json = xmlSerializer.read(xml)
//        } catch (Exception e) {
//            json.put(ResultModel.Code,ResultCode.SERVER_CONVERT_ERROR.code)
//            json.put(ResultModel.Msg,ResultCode.SERVER_CONVERT_ERROR.msg)
//            json.put(ResultModel.ServerErrorFlag,true)
//            json.put(ResultModel.Data,e.getMessage())
//            e.printStackTrace()
//        } finally {
            return json
//        }
    }


    static com.alibaba.fastjson.JSONObject getJsonObjectByXML_2(String xml) {

        def json = XmlUtils.xml2Json(xml)


        com.alibaba.fastjson.JSONObject Response = json.Response ?: ''

        com.alibaba.fastjson.JSONObject Body = Response.get("Body")

//        String result = Body.toString()
//        print "result"+Response.getClass().toString();
        return Body
    }

    static JSONObject getJsonObjectByXMLAndNode(String xml, String node) {

        def json = XML.toJSONObject(xml)
        def Header = json.getJSONObject(node).getJSONObject("Header")
        //println Header
        if ("SUCCESS".equals(String.valueOf(Header?.getString("RESULT") ?: "SUCCESS"))) {
            json = json.getJSONObject(node).getJSONObject("Body")
        } else {
            json = Header
        }
        return json
    }

    static String getXmlByJSON(Object obj) {
        def xml
        if (obj) {
            JSONObject jsonObject = new JSONObject(obj)
            xml = XML.toString(jsonObject)
        }

        return xml
    }

    /**
     *
     * @param obj
     * @return
     */
    static String getXmlByJSONHtml(Object obj) {
        def xml
        if (obj) {
            JSONObject jsonObject = new JSONObject(obj)
            xml = XML.toString(jsonObject)
            xml = StringEscapeUtils.unescapeHtml(xml)
        }

        return xml
    }
    /**
     *  [json]
     * @param obj
     * @return
     */
    static String getXmlByJSONArray(String obj) {
        def xml
        if (obj) {
            JSONArray array = new JSONArray(obj)
            xml = JSONUtil.toXmlStr(array)
            xml = xml.replace("<array>", "")
            xml = xml.replace("</array>", "")
            xml = StringEscapeUtils.unescapeHtml(xml)
        }

        return xml
    }

    static net.sf.json.JSON testGetJson(String xml) {
        net.sf.json.JSON json
        try {
            XMLSerializer xmlSerializer = new XMLSerializer();
            json = xmlSerializer.read(xml)
            println json.toString()
        } catch (Exception e) {
            println json.toString()
            e.printStackTrace()
        } finally {
            return json
        }
    }

    /**
     * 带双引号的json
     * @param xmlSerializer
     * @param xmlReturn
     * @param node
     * @return
     */
    static net.sf.json.JSONObject getSFJSONObjectBy(xmlSerializer, xmlReturn, node) {

        try {
            net.sf.json.JSON jsonObj = xmlSerializer.read(xmlReturn);
            net.sf.json.JSONObject jsob = net.sf.json.JSONObject.fromObject(jsonObj);
            String newStr = jsob.get(node).toString().replaceAll("\\u005b\\u005d", "null")

            /**
             def j1 =XML.toJSONObject(xmlReturn)
             print "新方法j1=${j1}"
             net.sf.json.JSONObject j2 = net.sf.json.JSONObject.fromObject(j1.toString());
             print "新方法a=${j2.toString()}"
             */
            return net.sf.json.JSONObject.fromObject(newStr);
        } catch (Exception e) {
            e.printStackTrace()
        }
    }

    static String getDirFilePath(path, String htmlfileName, DiagramVersion) {
        def returnFile = new String(path);
        try {
            def dir = new File(path)
            println "正在查找文件：${htmlfileName}-${DiagramVersion}"
            dir?.eachFileRecurse { file ->
                String str = file.getAbsolutePath()
                //println str
                int a = str.indexOf(htmlfileName)
                if (file.isFile() && a != -1) {
                    //println "str.indexOf(htmlfileName):${a}"
                    //print str.substring(a+htmlfileName.length(),str.lastIndexOf("."))
                    int b = str.substring(a + htmlfileName.length(), str.length()).indexOf(DiagramVersion)
                    if (b != -1) {
                        //println "str.substring(a+htmlfileName.length(),str.length()).indexOf(DiagramVersion):${b}"
                        // println str
                        returnFile = str
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace()
        } finally {
            return returnFile
        }
    }


    static SmbFile getRemoteShareFiles(String remoteUrl, String user, String password, String searchFile) {
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(remoteUrl, user, password);
        SmbFile remoteFile = new SmbFile(remoteUrl, auth);
        def file
        if (remoteFile.exists()) {
            file = searchFileTree(remoteFile, searchFile)
        }
        return file
    }


    static SmbFile getRemoteShareFiles(String remoteUrl, String user, String password) {
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(remoteUrl, user, password);
        SmbFile remoteFile = new SmbFile(remoteUrl, auth);
        return remoteFile
    }

    static SmbFile searchFileTree(SmbFile remoteFile, String searchFile) {
        SmbFile file
        if (remoteFile.isDirectory()) {
            //println "正在找文件........."
            for (SmbFile f : remoteFile.listFiles()) {
                println f.getName()
                file = searchFileTree(f, searchFile)
                if (file) {
                    break
                }
            }
        } else if (remoteFile.isFile() && remoteFile.getName().indexOf(searchFile) != -1) {
            println "找到文件........."
            file = remoteFile
        }

        return file
    }

    /**
     * 针对{} 和 []  特殊处理，直接值为 null
     * @param json
     * @return
     */
    static String getFormatString(json) {
        def result = json?.toString().replaceAll("\\{\\}", "null").replaceAll("\\[\\]", "null")
        return result
    }

    /**
     * 将json 字符串转json对象
     * glory.xxd 2019-03-17
     * @param jsonStr
     * @return
     */
    static parseStr2Json(jsonStr){
        return jsonStr?net.sf.json.JSONObject.fromObject(jsonStr):null
    }

}